<template>
  <div class="rowItem">
    <div class="box">
      <!-- <el-radio-group @change="changeType" style="margin-bottom: 20px" fill="#006837" text-color="#fff"
        v-model="searchState.type" size="large">
        <el-radio-button label="viruses" value="viruses" />
        <el-radio-button label="bacteria" value="bacteria" />
        <el-radio-button label="fungi" value="fungi" />
      </el-radio-group> -->
      <el-form label-position="right" :model="searchState" label-width="auto" ref="formRef">
        <el-form-item label="Kingdoms:" prop="kingdoms">
          <el-select v-model="searchState.kingdoms" :loading="loading" loading-text="Loading..."
            placeholder="Please select kingdoms" @change="changeKingdoms">
            <el-option v-for="item in selectOptions.kingdoms" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Phylum:" prop="phylum">
          <el-select v-model="searchState.phylum" :loading="loading" loading-text="Loading..."
            placeholder="Please select phylum" @change="changePhylum">
            <el-option v-for="item in selectOptions.phylum" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Class:" prop="class">
          <el-select v-model="searchState.class" :loading="loading" loading-text="Loading..." @change="changeClass"
            placeholder="Please select class">
            <el-option v-for="item in selectOptions.class" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Order:" prop="order">
          <el-select v-model="searchState.order" :loading="loading" loading-text="Loading..." @change="changeOrder"
            placeholder="Please select order">
            <el-option v-for="item in selectOptions.order" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Family:" prop="family">
          <el-select v-model="searchState.family" :loading="loading" loading-text="Loading..." @change="changeFamily"
            placeholder="Please select family">
            <el-option v-for="item in selectOptions.family" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Genus:" prop="genus">
          <el-select v-model="searchState.genus" :loading="loading" loading-text="Loading..." @change="changeGenus"
            placeholder="Please select genus">
            <el-option v-for="item in selectOptions.genus" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="Species:" prop="species">
          <el-select v-model="searchState.species" :loading="loading" loading-text="Loading..."
            placeholder="Please select species">
            <el-option v-for="item in selectOptions.species" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="" style="float: right">
          <div>
            <el-button @click="search()" style="font-weight: bold" type="primary">Start search</el-button>
            <el-button @click="onReset" style="font-weight: bold" type="primary">Reset</el-button>
            <el-button @click="onExample" style="font-weight: bold" type="primary">For example</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="box">
      <div class="carouselBox">
        <el-carousel :interval="5000" width="100" height="400px" arrow="always">
          <el-carousel-item v-for="item in carouselList" :key="item">
            <el-image :src="item" style="width: 100%; height: 100%"></el-image>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
  </div>
  <div style="display: flex; justify-content: flex-end">
    <el-button type="primary" style="margin: 10px 0; font-weight: 550" @click="downloadSearchResult">Export complete
      table</el-button>
  </div>
  <div class="box whole-line">
    <el-table :data="tableData" v-loading="tableLoading" style="font-size: 17px" stripe>
      <el-table-column prop="id" sortable label="PrimerID" width="205">
        <template #default="scope">
          <a style="color: #0c4270 !important" href="#" @click="getInfo(scope.row)">{{ scope.row.id }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="PRIMER_PAIR_PRODUCT_SIZE" label="Product size" :sort-method="(a, b) => {
        return a.PRIMER_PAIR_PRODUCT_SIZE - b.PRIMER_PAIR_PRODUCT_SIZE;
      }
        " sortable width="150">
        <template #default="scope">
          {{ processData(scope.row.PRIMER_PAIR_PRODUCT_SIZE) }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="SCORE" :sort-method="(a, b) => {
        return a.SCORE - b.SCORE;
      }
        " label="Score" width="100">
        <template #default="scope">
          {{ processData(scope.row?.SCORE) }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="ORGANISM_NAME" label="Organism name" width="200">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=${scope.row.TAXID}`">{{
              scope.row.ORGANISM_NAME }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="SPECIES" label="Species" width="180">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.ncbi.nlm.nih.gov/taxonomy/?term=${scope.row.SPECIES}`">{{ scope.row.SPECIES }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="STRAIN" label="Strain" width="100" />
      <el-table-column sortable prop="TAXID" :sort-method="(a, b) => {
        return a.TAXID - b.TAXID;
      }
        " label="Taxid" width="100">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=${scope.row.TAXID}`">{{ scope.row.TAXID
            }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="GENOME_ID" label="Assembly" width="170">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.ncbi.nlm.nih.gov/datasets/genome/${scope.row.GENOME_ID}/`">{{
              processData(scope.row.GENOME_ID) }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="GENE_ID" label="Gene ID" width="180" />
      <!-- <el-table-column prop="TM" label="TM" width="100px" /> -->
      <!-- <el-table-column
        sortable
        prop="PRIMER_PAIR_PENALTY"
        label="Penalty"
        width="130"
      >
        <template #default="scope">
          {{ processData(scope.row.PRIMER_PAIR_PENALTY) }}
        </template>
      </el-table-column> -->
      <el-table-column v-if="searchState.type != 'fungi'" sortable prop="UniRef90" label="UniRef90" width="230">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.uniprot.org/uniref/${scope.row.UniRef90}`">{{ scope.row.UniRef90 }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="UniRef50" v-if="searchState.type != 'fungi'" label="UniRef50" width="220">
        <template #default="scope">
          <a style="color: #0c4270 !important" target="_blank"
            :href="`https://www.uniprot.org/uniref/${scope.row.UniRef50}`">{{ scope.row.UniRef50 }}</a>
        </template>
      </el-table-column>
      <el-table-column sortable prop="UniRef90_50" v-if="searchState.type != 'fungi'" label="UniRef90/50" width="150" />
    </el-table>
    <div style="margin: 10px 0; padding-bottom: 5px">
      <el-pagination v-model:current-page="pageState.page" v-model:page-size="pageState.pageSize"
        :page-sizes="[10, 20, 50, 100]" layout="->,sizes, prev, pager, next" :total="total" style="margin-bottom: 10px"
        @size-change="changePageSize" @current-change="changePage" />
    </div>
    <div ref="anchor"></div>
  </div>
  <!-- info弹窗 -->
  <el-dialog v-model="infoModal" width="1350px" style="margin-top: 20px !important">
    <SearchInfoData :infoRow="searchState" :type="searchState.type" :id="searchState.id" />
  </el-dialog>
</template>

<script setup>
import { downLoadBlobFile, downloadFile } from "@/api/mange.js";
import {
  getGeneData,
  getGeneDataPhylum,
  getGeneDataClass,
  getGeneDataOrder,
  getGeneDataSearch,
  getGeneDataFamily,
  getGeneDataGenus,
  getGeneDataSpecies,
  searchDownResDownload
} from "@/api/search.js";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import SearchInfoData from "@/components/SearchInfoData.vue";
import router from "@/router/index";
import { useRoute } from "vue-router";
import { processData } from "@/utils/common.js";
import { getHomeSearchData } from "@/api/search.js";
const route = useRoute();
// 查询数据
const searchState = ref({ type: "bacteria", page: 1, pageSize: 50 });
const loading = ref(false); //加载状态
// 表单ref
const formRef = ref(null);
// 锚点
const anchor = ref(null);
const imgUrl = "http://www.primerbanks.com/geneData/getPicture/1.png";
// 详情数据
const infoModal = ref(false);
// 分页配置
const pageState = ref({
  page: 1,
  pageSize: 10,
});
const tableLoading = ref(false); // 表格加载状态
// 数据条数
const total = ref(0);
const routePath = ref();
const carouselList = ref([
  "http://www.primerbanks.com/geneData/getBanner/Search_1.png",
  "http://www.primerbanks.com/geneData/getBanner/Search_2.png",
  "http://www.primerbanks.com/geneData/getBanner/Search_3.png",
]);
// 微生物数据
const tableData = ref([]);
watch(
  () => route.fullPath,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      searchState.value.type = newVal.split("/")[2];
      getKingdoms();
      onReset();
    }
  },
  {
    deep: true, // 深度监听
    // immediate: true, //写上它，初始化时也会调用监听
  }
);
onMounted(() => {
  localStorage.setItem("searchType", route.fullPath.split("/")[2]);
  searchState.value.type = localStorage.getItem("searchType");
  if (localStorage.getItem("searchData_status") == "true") {
    let data = JSON.parse(localStorage.getItem("searchData"));
    let dataType = JSON.parse(localStorage.getItem("homeSearchType"));
    if (!isEmptyObject(data)) {
      nextTick(() => {
        searchState.value.kingdoms = data[0];
        searchState.value.phylum = data[1];
        searchState.value.class = data[2];
        searchState.value.order = data[3];
        searchState.value.family = data[4];
        searchState.value.genus = data[5];
        searchState.value.species = data[6];
        search(dataType);
      });
    }
  }
  // 获取所有选择器数据
  getKingdoms();
});
const onSubmit = () => { };
// 重置表单
const onReset = () => {
  tableData.value = [];
  total.value = 0;
  formRef.value.resetFields();
  searchState.value.class = "";
};
const onExample = () => {
  console.log("searchState.value.type", searchState.value.type);
  console.log("location", localStorage.getItem("searchType"));
  let type = searchState.value.type;
  if (type == "viruses") {
    searchState.value.kingdoms = "Heunggongvirae";
    searchState.value.phylum = "Peploviricota";
    searchState.value.class = "Herviviricetes";
    searchState.value.order = "Herpesvirales";
    searchState.value.family = "Alloherpesviridae";
    searchState.value.genus = "Ictavirus";
    searchState.value.species = "Ictavirus ictaluridallo1";
  } else if (type == "fungi") {
    searchState.value.kingdoms = "None";
    searchState.value.phylum = "Ascomycota";
    searchState.value.class = "Sordariomycetes";
    searchState.value.order = "Magnaporthales";
    searchState.value.family = "Pyriculariaceae";
    searchState.value.genus = "Pyricularia";
    searchState.value.species = "Pyricularia oryzae";
  } else if (type == "bacteria") {
    searchState.value.kingdoms = "Bacillati";
    searchState.value.phylum = "Bacillota";
    searchState.value.class = "Bacilli";
    searchState.value.order = "Bacillales";
    searchState.value.family = "Bacillaceae";
    searchState.value.genus = "Bacillus";
    searchState.value.species = "Bacillus mycoides";
  }
  getKingdoms();
};
// 所有选择器数据
const selectOptions = ref({
  kingdoms: {},
});
// 判断是否为空对象
const isEmptyObject = (obj) => {
  return Object.keys(obj).length === 0;
};
// 查询表单数据
const search = (dataType) => {
  tableLoading.value = true;
  let params = {
    ...searchState.value,
    ...pageState.value,
  };
  params.type = dataType ? dataType : searchState.value.type;
  getGeneDataSearch(params).then((res) => {
    tableLoading.value = false;
    tableData.value = res.data.data;
    total.value = res.data.count;
  });
};
const downloadSearchResult = async () => {
  let params = {
    ...searchState.value,
  };
  params.type = searchState.value.type;
  console.log("params", params);
  delete params.page
  delete params.pageSize
  try {
    const res = await searchDownResDownload(params)
    if (res.data) {
      const elink = document.createElement('a');
      const name = res.headers["content-disposition"].split("filename=")[1];
      let fileName = name.replace(/"/g, '');
      elink.download = fileName;
      elink.style.display = 'none';
      const blob = new Blob([res.data], { type: 'application/x-msdownload' });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    } else {
      console.error('导出异常请联系管理员');
    }
  } catch (error) {
    console.log(error);
    console.error('导出异常请联系管理员');
  }

};
// 改变页数
const changePage = (val) => {
  pageState.value.page = val;
  search();
};
// 改变页面查询数量
const changePageSize = (val) => {
  pageState.value.page = 1;
  search();
};
// 通过PrimerID获取详情
const getInfo = (row) => {
  searchState.value.id = row.id;
  searchState.value.GeneID = row.GENE_ID;
  // 打开弹窗
  infoModal.value = true;
  /*  router.push({
     path: '/search/summary',
     query: {
       id: row.id,
       type: searchState.value.type
     },
   }) */
};
// 获取界的数据
const getKingdoms = () => {
  loading.value = true;
  // let params = {
  //   type: searchState.value.type,
  // };
  getGeneData(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.kingdoms = res.data.data;
  });
};
// 根据界获取门分类
const getPhylum = () => {
  loading.value = true;
  // const { type, kingdoms } = searchState.value;
  // let params = {
  //   type,
  //   kingdoms,
  // };
  getGeneDataPhylum(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.phylum = res.data.data;
  });
};
// 根据门获取纲分类
const getClass = () => {
  loading.value = true;
  // const { type, phylum } = searchState.value;
  // let params = {
  //   type,
  //   phylum,
  // };
  getGeneDataClass(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.class = res.data.data;
  });
};
// 根据门获取纲分类
const getGigaorder = () => {
  loading.value = true;
  getGeneDataOrder(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.order = res.data.data;
  });
};
// 根据目获取科分类
const getFamily = () => {
  loading.value = true;
  // const { type, order } = searchState.value;
  // let params = {
  //   type,
  //   order,
  // };
  getGeneDataFamily(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.family = res.data.data;
  });
};
// 根据科获取属信息
const getGenus = () => {
  loading.value = true;
  getGeneDataGenus(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.genus = res.data.data;
  });
};
// 根据属获取种信息
const getSpecies = () => {
  loading.value = true;
  // const { type, genus } = searchState.value;
  // let params = {
  //   type,
  //   genus,
  // };
  getGeneDataSpecies(searchState.value).then((res) => {
    loading.value = false;
    selectOptions.value.species = res.data.data;
  });
};
/* 更改选择框数据 */
// 选择三大类
const changeType = (val) => {
  console.log("changeType", val);
  localStorage.removeItem("searchData_status");
  localStorage.removeItem("searchData");
  total.value = 0;
  tableData.value = [];
  // 根据条件查询界并清空已选中的界
  getKingdoms();
  delete searchState.value.kingdoms;
  delete searchState.value.phylum;
  delete searchState.value.class;
  delete searchState.value.order;
  delete searchState.value.family;
  delete searchState.value.genus;
  delete searchState.value.species;
};
// 选择Kingdom
const changeKingdoms = (val) => {
  if (searchState.value.kingdoms) {
    delete searchState.value.phylum;
    delete searchState.value.class;
    delete searchState.value.order;
    delete searchState.value.family;
    delete searchState.value.genus;
    delete searchState.value.species;
    selectOptions.value.phylum = [];
    selectOptions.value.class = [];
    selectOptions.value.order = [];
    selectOptions.value.family = [];
    selectOptions.value.genus = [];
    selectOptions.value.species = [];
  }
  // 根据条件查询界并清空已选中的界
  getPhylum();
};
// 选择Phylum
const changePhylum = (val) => {
  if (searchState.value.phylum) {
    delete searchState.value.order;
    delete searchState.value.family;
    delete searchState.value.genus;
    delete searchState.value.species;
    selectOptions.value.order = [];
    selectOptions.value.family = [];
    selectOptions.value.genus = [];
    selectOptions.value.species = [];
  }
  getClass();
};
// 选择Class
const changeClass = (val) => {
  if (searchState.value.class) {
    delete searchState.value.family;
    delete searchState.value.genus;
    delete searchState.value.species;
    selectOptions.value.family = [];
    selectOptions.value.genus = [];
    selectOptions.value.species = [];
  }
  searchState.value.class = val;
  getGigaorder();
};
// 选择Gigaorder
const changeOrder = (val) => {
  if (searchState.value.order) {
    delete searchState.value.genus;
    delete searchState.value.species;
    selectOptions.value.genus = [];
    selectOptions.value.species = [];
  }
  getFamily();
};
// 选择Family
const changeFamily = () => {
  if (searchState.value.family) {
    delete searchState.value.species;
    selectOptions.value.species = [];
  }
  getGenus();
};
// 选择Genus
const changeGenus = () => {
  getSpecies();
};
</script>
<style scoped lang="scss">
ul {
  list-style: none;
  padding: 10px;
}

ul li {
  display: flex;
  justify-content: space-between;
}

.rowItem {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.rowItem .box {
  width: 46.5%;
  padding: 20px;
}

.box {
  /* height: 200px; */

  /* border: 1px solid #d7d7d7; */
  /* padding: 20px; */
  box-shadow: 2px 2px 4px 2px #d7d7d7;
  margin-bottom: 30px;
}

.whole-line {
  width: 100%;
  box-sizing: content-box;

  .header {
    text-align: left;
    padding: 10px;
    border-bottom: 1px solid #d7d7d7;
  }

  .contentBox {
    padding: 20px;
    display: flex;
    justify-content: space-between;
    text-align: left;

    .left,
    .conter,
    .right {
      width: 30%;

      .title {
        padding: 10px;
        border-top: 2px solid #d7d7d7;
        border-bottom: 2px solid #d7d7d7;
      }
    }
  }
}

::v-deep .el-radio-button__inner:hover {
  color: #3b9d6e !important;
}

::v-deep .el-table__header th {
  background-color: #0c4270 !important;
  color: #fff;
}

::v-deep .el-table__header th {
  background-color: #0c4270 !important;
  color: #fff;
}

::v-deep .el-dialog {}

::v-deep .el-form-item__label {
  font-weight: bold;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background-color: #eff5fa;
}

::v-deep .el-table__header th {
  background-color: #4c7ce4 !important;
  color: #fff;
}

::v-deep .el-table__header {
  height: 60px !important;
}

::v-deep .el-card__header {
  padding: 8px;
  background-color: #0c4270 !important;
  color: #fff;
  font-weight: bold;
}

::v-deep .el-table__header th {
  background-color: #0c4270 !important;
  color: #fff;
}

::v-deep .el-form-item__label {
  font-size: 16px !important;
}
</style>